<?php
namespace api\service;

use api\service\interfaces\ISaleService;
use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\core\Log;
use herosphp\utils\AjaxResult;
use herosphp\utils\Page;
use models\TradingOrderModel;
use utils\x1\MyFunction;
use common\service\CommonService;

Loader::import('api.service.interfaces.ISaleService');
Loader::import('utils.x1.MyFunction');

/**
 * Sale api(Service)接口实现
 * @author yu
 */
class SaleService extends CommonService implements ISaleService
{

    private $thisModel = null;

    public function __construct()
    {
        $this->thisModel = Loader::model('tradingSale');
        Loader::model('tradingOrder');//引入TradingOrderModel类

    }

    //销售排行
    public function searchByRanking($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = " And o.order_status='" . TradingOrderModel::ORDER_STATUS_COMPLETED . "'";

        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(o.order_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));

        }

        if (in_array($search_arr['select_mix_option1'], array('product_no'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'product_no':

                    $whereSql .= " And p.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }

        $count_sql = "Select  p.id
                From product As p
                Left Join trading_order_product As o_p On o_p.product_id=p.id
                Left Join trading_order As o On o.id=o_p.order_id
                Where 1 $whereSql GROUP By p.product_no";
        $total_items=$this->thisModel->getDB()->excute($count_sql)->fetchAll($fetch_style = 2);
        $total=count($total_items);
        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select sum(o_p.product_actual_price) As total_sale_amount,sum(p.cost_price*o_p.product_quantity) As total_cost_price,sum(o_p.product_quantity) As total_sale_quantity,p.*
                From product As p
                Left Join trading_order_product As o_p On o_p.product_id=p.id
                Left Join trading_order As o On o.id=o_p.order_id
                Where 1 $whereSql
                GROUP By p.product_no  Order By total_sale_quantity DESC $pageinationSql";
        //echo $sql;

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);

        return new AjaxResult(AjaxResult::OP_SUCCESS, "loading successfully", array("items" => $items, "total" => $total));

    }

    //销售明细
    public function searchByDetails($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = " And o.order_status='7'";

        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(o.order_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));

        }
        if ($search_arr['appid'] != '') {

            $whereSql .= " And o.app_id='{$search_arr['appid']}'";

        }
        if (in_array($search_arr['select_mix_option1'], array('order_no', 'product_no'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'order_no':

                    $whereSql .= " And o.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
                case 'product_no':

                    $whereSql .= " And p.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }

        $count_sql = "Select  count(*)
                From trading_order_product As o_p
                Left Join trading_order as o On o_p.order_id=o.id
                Left Join product As p On o_p.product_id=p.id
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select o.app_id,o_p.product_actual_price As sale_amount,o_p.cost_price,o_p.product_quantity As sale_quantity,
                o.order_no,o.pay_way,o.order_time,p.product_name,p.brand_name,p.factory_name,p.type_name,p.product_no,p.pkg_size
                From trading_order_product As o_p
                Left Join trading_order as o On o_p.order_id=o.id
                Left Join product As p On o_p.product_id=p.id
                Where 1 $whereSql ORDER BY order_time DESC
                $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);

        $itemsLen = count($items);
        $saleService = Beans::get('trading.tradingOrder.service');
        for ($i = 0; $i < $itemsLen; $i++) {
            if ($items[$i]['cost_price'] == 0) {//成本价为空，不计算利润

                $items[$i]['sale_profit'] = '--';
            } else {

                $items[$i]['sale_profit'] = $items[$i]['sale_amount'] - ($items[$i]['cost_price'] * $items[$i]['sale_quantity']);

            }
            $items[$i]['pay_way'] = $saleService->getPaywayText($items[$i]['pay_way']);
        }

        return new AjaxResult(AjaxResult::OP_SUCCESS, "loading successfully", array("items" => $items, "total" => $total));
    }

    //财务统计
    public function searchByFinance($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "";

        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(trading_sale_profit.that_day)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));

        }

        /*此选项暂时屏蔽，目前还不明确需求*/
        /*if (in_array($search_arr['select_mix_option1'], array('product_no'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'product_no':

                    $whereSql .= " And p.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }*/

        if ($search_arr['appid'] != '') {
            $whereSql .= " And app_id = '{$search_arr['appid']}'";
        }

        $count_sql = "Select  count(*)
                From trading_sale_profit
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select *
                From trading_sale_profit
                Where 1 $whereSql Order By that_day Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);
        Log::info($sql);

        return new AjaxResult(AjaxResult::OP_SUCCESS, "loading successfully", array("items" => $items, "total" => $total));
    }
}
